package com.caiyi.financial.nirvana.sms;

import com.caiyi.financial.nirvana.sms.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.cmpp.CharsetInfo;
import com.caiyi.financial.nirvana.sms.cmpp20.message.CMPPMessage;
import com.caiyi.financial.nirvana.sms.cmpp20.message.body.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

public class CMPPClientHandler extends SimpleChannelInboundHandler<CMPPMessage> {

    private static final Logger logger = LoggerFactory.getLogger(CMPPClientHandler.class);
    public final AtomicInteger seqNo = new AtomicInteger(1);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        CMPPMessage loginMessage = new CMPPMessage();
        CMPPConnection cmppConnection = new CMPPConnection("985764", "TMsgT3");
        loginMessage.setCommandID(CMPPMessage.CMPP_CONNECT);
        loginMessage.setSequenceId(seqNo.getAndIncrement());
        loginMessage.setBody(cmppConnection);
        ctx.writeAndFlush(loginMessage);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.info("exceptionCaught .......");
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CMPPMessage msg) throws Exception {
        int commandId = msg.getCommandID();
        switch (commandId) {
            //如果收到心跳包，不处理
            case CMPPMessage.CMPP_ACTIVE_TEST_RESP:
                break;
            //如果收到心跳包，回复网关
            case CMPPMessage.CMPP_ACTIVE_TEST:
                CMPPMessage messageTest = new CMPPMessage();
                messageTest.setSequenceId(msg.getSequenceId());
                messageTest.setCommandID(CMPPMessage.CMPP_ACTIVE_TEST_RESP);
                CMPPActiveTestResp activeTestResp = new CMPPActiveTestResp();
                messageTest.setBody(activeTestResp);
                ctx.writeAndFlush(messageTest);
                break;
            //连接回应
            case CMPPMessage.CMPP_CONNECT_RESP:
                CMPPConnectionResp resp = (CMPPConnectionResp) msg.getBody();
                logger.debug("CMPP_CONNECT_RESP...status : {}", resp.getStatus());
                if (resp.getStatus() == 0) {
                    submit(ctx);
                }
                break;
            //获得上行短信
            case CMPPMessage.CMPP_DELIVER:
                deliverResp(ctx, msg);
                break;
            //获得消息发送返回值
            case CMPPMessage.CMPP_SUBMIT_RESP:
                logger.debug("CMPP_SUBMIT_RESP.......");
                break;
            default:
                break;
        }
    }

    private void deliverResp(ChannelHandlerContext ctx, CMPPMessage msg) {
        logger.info("deliverResp   statue is {}", ((CMPPDeliver) msg.getBody()).getStat());
        CMPPMessage message = new CMPPMessage();
        CMPPDeliverResp deliverResp = new CMPPDeliverResp();
        message.setCommandID(CMPPMessage.CMPP_DELIVER_RESP);
        message.setBody(deliverResp);
        deliverResp.setResult((byte) 0);
        deliverResp.setMessageId(((CMPPDeliver) msg.getBody()).getMessageId());
        ctx.writeAndFlush(message);
    }

    private void submit(ChannelHandlerContext ctx) {
        for (int i = 0; i < 10000; i++) {
            String phone = "18117351521";
            switch (i % 3) {
                case 0:
                    phone = ("176212") + (String.format("%05d", i));
                    break;
                case 1:
                    phone = ("150212") + (String.format("%05d", i));
                    break;
                case 2:
                    phone = ("189212") + (String.format("%05d", i));
                    break;
            }
            CMPPSubmit submit = new CMPPSubmit();
            submit.setLevel((byte) 10);
            submit.setSpId("1qw123");
            submit.setSrcId("122");
            submit.setDestTerminalId(new String[]{phone});
            submit.setMessageContent("【测试签名】你的验证码是：" + i);
            submit.setMessageFormat(CharsetInfo.UCS2);
            submit.setServiceId("");
            CMPPMessage message = new CMPPMessage();
            CMPPHeader header = new CMPPHeader();
            header.setCommandID(CMPPMessage.CMPP_SUBMIT);
            message.setHeader(header);
            message.setSequenceId(1);
            message.setBody(submit);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //读空闲事件，触发重连，关闭当前连接；否则发送心跳包给服务器
            if (event.state().equals(IdleState.READER_IDLE)) {
                logger.info(" 读空闲事件，连接关闭！");
                ctx.close();
            } else {
                logger.info(" 心跳测试。");
                CMPPMessage message = new CMPPMessage();
                message.setCommandID(CMPPMessage.CMPP_ACTIVE_TEST);
                message.setSequenceId(seqNo.incrementAndGet());
                CMPPActiveTest activeTest = new CMPPActiveTest();
                message.setBody(activeTest);
                ctx.writeAndFlush(message);
            }
        }
    }
}
